<?php
/**
 * 张榜
 * 更新时间：每周三，0点
 */
ini_set('display_errors', 1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';

use Biz\cache\wiki\WikiRanking as cacheWikiRanking;
use Biz\model\wiki\WikiRankingBrand;
use Biz\model\wiki\WikiRankingConfig;
use Biz\model\wiki\WikiRankingHot;
use Biz\model\wiki\WikiRankingPublicPraise;
use Biz\model\wiki\WikiRankingWeek;
use Biz\service\wikiRanking\Ranking;

$start = time();
$dayArr = Ranking::getCreateRankingDay();
$day = $dayArr['day'];
$now = date('Ymd');
if ($day != $now) {
    var_dump('当前日期为：' . $now . '不能张第「' . $day . '」的榜单');
    return false;
}
$info = WikiRankingWeek::getByWhere(['ranking_day' => $day]);
if (!$info) {
    var_dump('不存在的榜单期数');
    return false;
}

$allRankingList = WikiRankingConfig::selectByWhere(['config_state[!]' => WikiRankingConfig::CONFIG_STATE_DEL, 'pid[>]' => 0, 'deep' => 2], ['id', 'ranking_name']);
$allRankingList = array_column($allRankingList, null, 'id');
$lastWeekDay = getLastWeekDay($day);
$brandRankingNameForMsg = [];
foreach ($allRankingList as $rankingId => $configInfo) {
    $rankingName = $configInfo['ranking_name'];
    $where = [
        'ranking_day' => $day,
        'ranking_id' => $rankingId,
        'ranking_state[!]' => WikiRankingHot::RANKING_STATE_DEL,
        'ORDER' => ['score' => 'DESC']
    ];
    $rankingData = [
        'show_hot' => [],
        'hide_hot' => [],
        'show_public_praise' => [],
        'hide_public_praise' => [],
        'show_brand' => [],
        'hide_brand' => []
    ];
    //热度榜张榜中
    var_dump($rankingId . '#「' . $rankingName . '」热度榜张榜中……');
    $hotList = WikiRankingHot::selectByWhere($where);
    foreach ($hotList as $index => $row) {
        $topNum = $index + 1;
        if ($index > 19) {
            $rankingData['hide_hot'][] = [
                'id' => $row['id'],
                'brand_id' => $row['brand_id'],
                'basic_id' => $row['basic_id'],
                'top_num' => $topNum,
            ];
        } else {
            $rankingData['show_hot'][] = [
                'id' => $row['id'],
                'brand_id' => $row['brand_id'],
                'basic_id' => $row['basic_id'],
                'top_num' => $topNum,
            ];
        }
        $lastTopNum = $lastWeekDay ? WikiRankingHot::getByWhere(['ranking_day' => $lastWeekDay, 'ranking_id' => $rankingId, 'basic_id' => $row['basic_id'], 'ranking_state[!]' => WikiRankingHot::RANKING_STATE_DEL], 'top_num') : 0;
        $lastTopNum = !empty($lastTopNum) ? $lastTopNum : 0;
        WikiRankingHot::updateData(['top_num' => $topNum, 'last_top_num' => $lastTopNum], ['id' => $row['id']]);
    }

    //口碑榜张榜中
    var_dump($rankingId . '#「' . $rankingName . '」口碑榜张榜中……');
    $publicPraiseList = WikiRankingPublicPraise::selectByWhere($where);
    foreach ($publicPraiseList as $index => $row) {
        $topNum = $index + 1;
        if ($index > 19) {
            $rankingData['hide_public_praise'][] = [
                'id' => $row['id'],
                'brand_id' => $row['brand_id'],
                'basic_id' => $row['basic_id'],
                'top_num' => $topNum,
            ];
        } else {
            $rankingData['show_public_praise'][] = [
                'id' => $row['id'],
                'brand_id' => $row['brand_id'],
                'basic_id' => $row['basic_id'],
                'top_num' => $topNum,
            ];
        }
        $lastTopNum = $lastWeekDay ? WikiRankingPublicPraise::getByWhere(['ranking_day' => $lastWeekDay, 'ranking_id' => $rankingId, 'basic_id' => $row['basic_id'], 'ranking_state[!]' => WikiRankingPublicPraise::RANKING_STATE_DEL], 'top_num') : 0;
        $lastTopNum = !empty($lastTopNum) ? $lastTopNum : 0;
        WikiRankingPublicPraise::updateData(['top_num' => $topNum, 'last_top_num' => $lastTopNum], ['id' => $row['id']]);
    }

    //品牌榜张榜中
    var_dump($rankingId . '#「' . $rankingName . '」品牌榜张榜中……');
    $brandList = WikiRankingBrand::selectByWhere($where);
    foreach ($brandList as $index => $row) {
        $topNum = $index + 1;
        if ($index > 19) {
            $rankingData['hide_brand'][] = [
                'id' => $row['id'],
                'brand_id' => $row['brand_id'],
                'basic_id' => $row['basic_id'],
                'top_num' => $topNum,
            ];
        } else {
            $rankingData['show_brand'][] = [
                'id' => $row['id'],
                'brand_id' => $row['brand_id'],
                'basic_id' => $row['basic_id'],
                'top_num' => $topNum,
            ];
        }
        $lastTopNum = $lastWeekDay ? WikiRankingBrand::getByWhere(['ranking_day' => $lastWeekDay, 'ranking_id' => $rankingId, 'brand_id' => $row['brand_id'], 'ranking_state[!]' => WikiRankingBrand::RANKING_STATE_DEL], 'top_num') : 0;
        $lastTopNum = !empty($lastTopNum) ? $lastTopNum : 0;
        WikiRankingBrand::updateData(['top_num' => $topNum, 'last_top_num' => $lastTopNum], ['id' => $row['id']]);
    }
    showRanking($day, $rankingId, $rankingName, $rankingData, $brandRankingNameForMsg);
}

foreach ($brandRankingNameForMsg as $brandId => $row) {
    $msg = '恭喜你被住友选入了新一期 %s 中，打开好好住 App 进入好物频道就可以看到上榜情况了，想要玩转榜单就快点击这里查看《榜单秘籍》吧';
    $msgTemp = implode('、', $row);
    $msg = sprintf($msg, $msgTemp);
    \Biz\service\BrandIndex::writeMsg($brandId, \Biz\model\brandIndex\BrandMsg::MSG_TYPE_PASS, \Biz\model\brandIndex\BrandMsg::MSG_SOURCE_RANKING, $msg);
}
$end = time();
var_dump(date('Y-m-d-H-i-s') . '第' . $day . '期榜单张榜完成,耗时:' . ($end - $start) . '秒，' . (($end - $start) / 60) . '分');
//50秒

var_dump('更新连续上榜次数');
$rankingDay = $day;
$weekDays = WikiRankingWeek::selectByWhere(['ranking_day[<]' => $rankingDay, 'ORDER' => ['ranking_day' => 'DESC']], 'ranking_day');
var_dump($weekDays);

$where = ['ranking_day' => $rankingDay, 'ranking_state' => WikiRankingHot::RANKING_STATE_SHOW];
$hotList = WikiRankingHot::selectByWhere($where);
foreach ($hotList as $row) {
    $continueWeek = 1;
    foreach ($weekDays as $weekDay) {
        $info = WikiRankingHot::getByWhere(['ranking_day' => $weekDay, 'ranking_state' => WikiRankingHot::RANKING_STATE_SHOW, 'basic_id' => $row['basic_id'], 'ranking_id' => $row['ranking_id']]);
        if (!empty($info)) {
            $continueWeek = $continueWeek + 1;
        } else {
            break;
        }
    }
    var_dump('截止到' . $rankingDay . '#榜单id：' . $row['ranking_id'] . '#basic Id：' . $row['basic_id'] . '#连续上热度榜:' . $continueWeek . '次');
    WikiRankingHot::updateData(['continue_week' => $continueWeek], ['ranking_id' => $row['ranking_id'], 'ranking_day' => $rankingDay, 'basic_id' => $row['basic_id']]);
}
$publicPraiseList = WikiRankingPublicPraise::selectByWhere($where);
foreach ($publicPraiseList as $row) {
    $continueWeek = 1;
    foreach ($weekDays as $weekDay) {
        $info = WikiRankingPublicPraise::getByWhere(['ranking_day' => $weekDay, 'ranking_state' => WikiRankingPublicPraise::RANKING_STATE_SHOW, 'basic_id' => $row['basic_id'], 'ranking_id' => $row['ranking_id']]);
        if (!empty($info)) {
            $continueWeek = $continueWeek + 1;
        } else {
            break;
        }
    }
    var_dump('截止到' . $rankingDay . '#榜单id：' . $row['ranking_id'] . '#basic Id：' . $row['basic_id'] . '#连续上口碑榜:' . $continueWeek . '次');
    WikiRankingPublicPraise::updateData(['continue_week' => $continueWeek], ['ranking_id' => $row['ranking_id'], 'ranking_day' => $rankingDay, 'basic_id' => $row['basic_id']]);
}

$brandList = WikiRankingBrand::selectByWhere($where);
foreach ($brandList as $row) {
    $continueWeek = 1;
    foreach ($weekDays as $weekDay) {
        $info = WikiRankingBrand::getByWhere(['ranking_day' => $weekDay, 'ranking_state' => WikiRankingBrand::RANKING_STATE_SHOW, 'brand_id' => $row['brand_id'], 'ranking_id' => $row['ranking_id']]);
        if (!empty($info)) {
            $continueWeek = $continueWeek + 1;
        } else {
            break;
        }
    }
    var_dump('截止到' . $rankingDay . '#榜单id：' . $row['ranking_id'] . '#brand Id：' . $row['brand_id'] . '#连续上品牌榜:' . $continueWeek . '次');
    WikiRankingBrand::updateData(['continue_week' => $continueWeek], ['ranking_id' => $row['ranking_id'], 'ranking_day' => $rankingDay, 'brand_id' => $row['brand_id']]);
}

var_dump('设置上榜榜单id缓存');
Ranking::setShowRankingIds();


function showRanking($day, $rankingId, $rankingName, $rankingData, &$brandRankingNameForMsg)
{
    $showHotData = $rankingData['show_hot'];
    $hideHotData = $rankingData['hide_hot'];
    $showPublicPraiseData = $rankingData['show_public_praise'];
    $hidePublicPraiseData = $rankingData['hide_public_praise'];
    $showBrandData = $rankingData['show_brand'];
    $hideBrandData = $rankingData['hide_brand'];

    //分类榜单下，Tab 下不少于 5 条数据的才可展示；
    //二级分类下有不少于两个榜（如热度榜+口碑榜、热度榜+品牌榜），且当前热度榜有大于等于 5 个 Wiki 的榜单才计为有效榜单；
    //仅有效榜单才可在各曝光位被推荐或被搜索或在相关商品和品牌主页中作为标签展示。
    //热度榜
    if (count($showHotData) < 5) {
        $hideHotData = array_merge($hideHotData, $showHotData);
        $showHotData = [];
    }
    if (count($showPublicPraiseData) < 5) {
        $hidePublicPraiseData = array_merge($hidePublicPraiseData, $showPublicPraiseData);
        $showPublicPraiseData = [];
    }
    if (count($showBrandData) < 5) {
        $hideBrandData = array_merge($hideBrandData, $showBrandData);
        $showBrandData = [];
    }
    if ($showHotData) {
        if (empty($showPublicPraiseData) && empty($showBrandData)) {
            var_dump('******未满足上榜条件#ranking_id:' . $rankingId . '#ranking_name:' . $rankingName);
            $hideHotData = array_merge($hideHotData, $showHotData);
            $showHotData = [];
        }
    }

    //热度榜单缓存
    if ($showHotData) {
        foreach ($showHotData as $index => $row) {
            $topNum = $row['top_num'];
            cacheWikiRanking::addBasicWikiHotRanking($day, $row['basic_id'], $topNum, $rankingId);
            if ($row['brand_id']) {
                $brandRankingName = $rankingName . '榜';
                if (!isset($brandRankingNameForMsg[$row['brand_id']])) {
                    $brandRankingNameForMsg[$row['brand_id']][] = $brandRankingName;
                } else if (!in_array($brandRankingName, $brandRankingNameForMsg[$row['brand_id']])) {
                    $brandRankingNameForMsg[$row['brand_id']][] = $brandRankingName;
                }
            }
            $data = [
                'ranking_state' => WikiRankingHot::RANKING_STATE_SHOW,
            ];
            WikiRankingHot::updateData($data, ['id' => $row['id']]);
        }
    }
    if ($hideHotData) {
        foreach ($hideHotData as $row) {
            $data = [
                'ranking_state' => WikiRankingHot::RANKING_STATE_HIDE,
            ];
            WikiRankingHot::updateData($data, ['id' => $row['id']]);
        }
    }

    //口碑榜
    if ($showPublicPraiseData) {
        foreach ($showPublicPraiseData as $index => $row) {
            $topNum = $row['top_num'];
            //口碑榜单缓存
            cacheWikiRanking::addBasicWikiPublicPraiseRanking($day, $row['basic_id'], $topNum, $rankingId);
            if ($row['brand_id']) {
                $brandRankingName = $rankingName . '榜';
                if (!isset($brandRankingNameForMsg[$row['brand_id']])) {
                    $brandRankingNameForMsg[$row['brand_id']][] = $brandRankingName;
                } else if (!in_array($brandRankingName, $brandRankingNameForMsg[$row['brand_id']])) {
                    $brandRankingNameForMsg[$row['brand_id']][] = $brandRankingName;
                }
            }
            $data = [
                'ranking_state' => WikiRankingPublicPraise::RANKING_STATE_SHOW,
            ];
            WikiRankingPublicPraise::updateData($data, ['id' => $row['id']]);
        }
    }
    if ($hidePublicPraiseData) {
        foreach ($hidePublicPraiseData as $row) {
            $data = [
                'ranking_state' => WikiRankingPublicPraise::RANKING_STATE_HIDE,
            ];
            WikiRankingPublicPraise::updateData($data, ['id' => $row['id']]);
        }
    }

    //品牌榜
    if ($showBrandData) {
        foreach ($showBrandData as $index => $row) {
            $topNum = $row['top_num'];
            //品牌榜单缓存
            cacheWikiRanking::addBrandRanking($day, $row['brand_id'], $topNum, $rankingId);
            if ($row['brand_id']) {
                $brandRankingName = $rankingName . '榜';
                if (!isset($brandRankingNameForMsg[$row['brand_id']])) {
                    $brandRankingNameForMsg[$row['brand_id']][] = $brandRankingName;
                } else if (!in_array($brandRankingName, $brandRankingNameForMsg[$row['brand_id']])) {
                    $brandRankingNameForMsg[$row['brand_id']][] = $brandRankingName;
                }
            }
            $data = [
                'ranking_state' => WikiRankingBrand::RANKING_STATE_SHOW,
            ];
            WikiRankingBrand::updateData($data, ['id' => $row['id']]);
        }
    }
    if ($hideBrandData) {
        foreach ($hideBrandData as $row) {
            $data = [
                'ranking_state' => WikiRankingBrand::RANKING_STATE_HIDE,
            ];
            WikiRankingBrand::updateData($data, ['id' => $row['id']]);
        }
    }
}

function getLastWeekDay($day)
{
    $lastWeekInfo = WikiRankingWeek::getByWhere(['ORDER' => ['ranking_day' => 'DESC'], 'ranking_day[<]' => $day]);
    $lastWeekDay = $lastWeekInfo ? $lastWeekInfo['ranking_day'] : 0;
    return $lastWeekDay;
}